package admin

import (
	"SlowAdmin/controllers"
	"SlowAdmin/models"
	"encoding/json"
)

// ApiController api控制器
type ApiController struct {
	controllers.BaseController
}

var adminApiModel = models.AdminApi{}

// @title 获取列表
func (c *ApiController) List() {
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 15)

	list, total := adminApiModel.GetList(page, pageSize)

	c.Success("ok", controllers.Result{
		"list":      list,
		"total":     total,
		"page":      page,
		"page_size": pageSize,
	})
}

// @title 获取分组信息
func (c *ApiController) Group() {
	c.Success("ok", adminApiModel.GetGroup())
}

// @title 删除
func (c *ApiController) Delete() {
	var data map[string]string
	json.Unmarshal(c.Ctx.Input.RequestBody, &data)

	err := adminApiModel.Delete(data["ids"])

	if err != nil {
		c.Fail("删除失败", controllers.Result{
			"error": err.Error(),
		})
		return
	}

	c.Success("删除成功", nil)
}

// @title 查询单个
func (c *ApiController) Find() {
	id := c.Ctx.Input.Param(":id")
	if id == "" {
		c.Fail("id不能为空", nil)
		return
	}

	c.Success("查询成功", adminApiModel.GetOne(id))
}

// @title 添加
func (c *ApiController) Store() {
	json.Unmarshal(c.Ctx.Input.RequestBody, &adminApiModel)

	err := adminApiModel.Store()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("添加成功", nil)
}

// @title 修改
func (c *ApiController) Update() {
	json.Unmarshal(c.Ctx.Input.RequestBody, &adminApiModel)

	if adminApiModel.Id == 0 {
		c.Fail("id不能为空", nil)
		return
	}

	err := adminApiModel.Update()

	if err != nil {
		c.Fail(err.Error(), nil)
		return
	}

	c.Success("更新成功", nil)
}
